<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@ page import="com.geping.etl.utils.EnvUitl" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
    String usersMerge = EnvUitl.props.getProperty("users.merge");
    String east2Huachen = (String) request.getSession().getAttribute("east2Huachen");
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <base href="<%=basePath%>">

    <title>角色管理</title>
    <%@include file="head.jsp" %>
</head>
<body class="easyui-layout">

<!-- 西 -->
<!-- data-options="singleSelect:true,rownumbers:true,toolbar:'#tb',autoRowHeight:false,pagination:true,pageSize:25,pageList:[15,25,35] -->
<%--<div data-options="region:'west',split:true,title:'子系统列表',rownumbers:true,idField:'id', pageSize:50" style="width:350px;padding: 10px">
	<table title="系统名称" id="dg1" style="height: 440px"></table>
</div>--%>


<!-- 中 -->
<div data-options="region:'center'" style="width:650px">
    <table title="角色管理信息" id="dg2" style="height: 440px"></table>

    <div id="tb" style="padding: 5px; height: auto">
        角色名称: <input type="text" style="width: 173px; height: 21px"
                         id="roleName" name="roleName" value="${name}">&nbsp;&nbsp; <a
            class="easyui-linkbutton" iconCls="icon-search"
            onclick="selectRecordByName()">查询</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <a class="easyui-linkbutton" iconCls="icon-add" onclick="addRole()">新增</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <a class="easyui-linkbutton" iconCls="icon-edit" onclick="editRole()">修改</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <!-- <a class="easyui-linkbutton" iconCls="icon-remove" onclick="remove()">删除角色</a>-->
        <a class="easyui-linkbutton" iconCls="icon-remove" onclick="stopRole()">停用角色</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <a class="easyui-linkbutton" iconCls="icon-edit" onclick="roleResource()">角色资源管理</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    </div>
</div>


<!-- 新增角色dialog -->
<div style="visibility: hidden;">

    <div id="addDialog" class="easyui-dialog" title="新增角色"
         data-options="iconCls:'icon-save',toolbar:'#tbForAddDialog'"
         style="width: 500px; height: 200px; top: 200px">
        <!--   新增对话框的工具栏  -->
        <div id="tbForAddDialog"
             style="padding-left: 30px; padding-top: 10px">
            <a id="saveButtonId" class="easyui-linkbutton" data-options="iconCls:'icon-save'"
               onclick="saveForAddDialog()">保存</a>&nbsp;&nbsp; <a
                class="easyui-linkbutton" data-options="iconCls:'icon-undo'"
                onclick="resetforAdd()">重置</a>
        </div>

        <form id="formForAddRole" method="post">
            <div style="padding-top: 20px">
                <table style="padding-left: 30px">
                    <input type="hidden" name="randSession" value="<%=request.getSession().getAttribute("authId")%>"/>
                    <input type="hidden" id="subjectIdAdd" name="subjectIdAdd"/>
                    <tr>
                        <td align="right">角色名称:</td>
                        <td><input type="text" class="easyui-validatebox" name="roleNameadd"
                                   id="roleNameadd" data-options="required:true,missingMessage:'角色名称不能为空'"
                                   style="height: 21px;width: 173px"/></td>
                    </tr>

                    <tr>
                        <td align="right">角色描述:</td>
                        <td><input type="text" class="easyui-validatebox" name="roleDescadd"
                                   id="roleDescadd"
                                   data-options="required:true,missingMessage:'角色描述不能为空'"
                                   style="height: 21px;width: 173px"/></td>
                    </tr>

                </table>
            </div>
        </form>
    </div>
</div>

<!-- 修改角色 -->
<div style="visibility: hidden;">
    <div id="editDialog" class="easyui-dialog" title="修改用户信息"
         data-options="iconCls:'icon-save',toolbar:'#tbForEditDialog'"
         style="width: 500px; height: 200px; top: 200px">
        <!--修改对话框的工具栏  -->
        <div id="tbForEditDialog"
             style="padding-left: 30px; padding-top: 10px">
            <a id="editButtonId" class="easyui-linkbutton" data-options="iconCls:'icon-save'"
               onclick="saveForEditDialog()">保存</a>&nbsp;&nbsp; <a
                class="easyui-linkbutton" data-options="iconCls:'icon-undo'"
                onclick="resetforEdit()">重置</a>
        </div>

        <form id="formForEditRole" method="post">
            <div style="padding-top: 20px">
                <table style="padding-left: 30px">
                    <input type="hidden" name="randSession" value="<%=request.getSession().getAttribute("authId")%>"/>
                    <input type="hidden" name="editId" id="editId"/>
                    <input type="hidden" name="isEditRoleName" id="isEditRoleName"/>
                    <input type="hidden" name="subjectIdUpdate" id="subjectIdUpdate"/>
                    <tr>
                        <td align="right">角色名称:</td>
                        <td><input type="text" class="easyui-validatebox" name="roleNameEdit"
                                   id="roleNameEdit"
                                   data-options="required:true,missingMessage:'角色名称不能为空'"
                                   style="height: 21px;width: 173px"/></td>
                    </tr>

                    <tr>
                        <td align="right">角色描述:</td>
                        <td><input type="text" class="easyui-validatebox" name="roleDescEdit"
                                   id="roleDescEdit" data-options="required:true,missingMessage:'角色描述不能为空'"
                                   style="height: 21px;width: 173px"/></td>
                    </tr>

                </table>
            </div>
        </form>

    </div>


</div>

<!-- 角色资源分配 -->
<div style="visibility: hidden;">
    <div id="roleResourDialog" class="easyui-dialog" title="角色资源管理" style="width: 800px; height:500px"
         data-options="iconCls:'icon-save',toolbar:'#tbForRoleResourceDialog'">
        <div style="margin:10px 0;"></div>
        <div class="easyui-tabs" style="width:770px;height:400px;margin-left:10px">

            <div title="菜单权限" style="margin-top:10px;margin-left:10px">

                <table id="sysMenu" class="easyui-datagrid" style="width:750px;height:340px"
                       data-options="checkOnSelect:true,autoRowHeight:false,pagination:true,rownumbers:true,idField:'id', pageSize:130,pageList:[200]">
                    <thead>
                    <tr>
                        <th field="ck" checkbox="true"></th>
                        <th data-options="field:'id',width:230,align:'center'">编号</th>
                        <th data-options="field:'name',width:230,align:'center'">菜单名称</th>
                        <th data-options="field:'url',width:230,align:'center'">请求访问地址</th>
                    </tr>
                    </thead>

                </table>
            </div>

            <div title="报表权限" style="margin-top:10px;margin-left:10px">
                <c:if test="${east2Huachen==null||east2Huachen!='on'}">
                    <table id="reportInfo" class="easyui-datagrid" style="width:750px;height:340px"
                           data-options="checkOnSelect:true,autoRowHeight:false,pagination:true,rownumbers:true,idField:'id', pageSize:100,pageList:[100]">
                        <thead>
                        <tr>
                            <th field="ck" checkbox="true"></th>
                            <th data-options="field:'id',width:100,align:'center',hidden:true">ID</th>
                            <th data-options="field:'code',width:200,align:'center'">报表代码</th>
                            <th data-options="field:'name',width:245,align:'center'">报表名称</th>
                           <%-- <th data-options="field:'instruction',width:245,align:'center'">备注</th>--%>
                            <!-- <th data-options="field:'batch',width:80,align:'center'">批次</th> -->
                        </tr>
                        </thead>
                    </table>
                </c:if>
                <c:if test="${east2Huachen=='on'}">
                    <table id="reportInfo" class="easyui-datagrid" style="width:750px;height:340px"
                           data-options="checkOnSelect:true,autoRowHeight:false,pagination:true,rownumbers:true,idField:'id', pageSize:100,pageList:[100]">
                        <thead>
                        <tr>
                            <th field="ck" checkbox="true"></th>
                            <th data-options="field:'id',width:100,align:'center',hidden:true">ID</th>
                            <th data-options="field:'code',width:200,align:'center'">报表代码</th>
                            <th data-options="field:'name',width:200,align:'center'">报表名称</th>
                            <th data-options="field:'instruction',width:200,align:'center'">所属模块</th>
                        </tr>
                        </thead>
                    </table>
                </c:if>
            </div>


            <!--
                    <div title="机构权限" style="margin-top:10px;margin-left:10px" >
                        <table id="institutionalrolepermission" class="easyui-datagrid" style="width:750px;height:650px" data-options="checkOnSelect:true,singleSelect:true,autoRowHeight:false,pagination:true,rownumbers:true,idField:'id', pageSize:50">
                            <thead>
                                <tr>
                                    <th field="ck" checkbox="true"></th>
                                    <th data-options="field:'id',width:100,align:'center',hidden:true">ID</th>
                                    <th data-options="field:'orgId',width:345,align:'center'">机构代码</th>
                                    <th data-options="field:'orgName',width:345,align:'center'">机构名称</th>
                                </tr>
                            </thead>
                       </table>

                    </div>
                    -->
            <div title="报表操作权限" style="margin-top:10px;margin-left:10px">
                <table id="reportOperate" class="easyui-datagrid" style="width:750px;height:340px"
                       data-options="checkOnSelect:true,autoRowHeight:false,pagination:true,rownumbers:true,idField:'id', pageSize:100,pageList:[100]">
                    <thead>
                    <tr>
                        <th field="ck" checkbox="true"></th>
                        <th data-options="field:'id',width:100,align:'center',hidden:true">ID</th>
                        <th data-options="field:'reportOperateCode',width:345,align:'center'">操作权限代码</th>
                        <th data-options="field:'reportOperateName',width:345,align:'center'">操作权限名称</th>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>

        <div id="tbForRoleResourceDialog" style="padding-left: 30px; padding-top: 10px">
            <a class="easyui-linkbutton" data-options="iconCls:'icon-save'"
               onclick="saveForRoleResourceDialog()">保存</a>&nbsp;&nbsp;
            <a class="easyui-linkbutton" data-options="iconCls:'icon-undo'" onclick="cancel()">取消</a>
        </div>
    </div>
</div>


<script type="text/javascript">
    var roleName;
    var roleDesc;
    var isEdit_RoleName;
    //获取到要在角色资源管理中一同保存到角色资源对照表 的 Sys_Auth_Role中的id
    var roleId;
    var subjectId = '1';

    //初始化关闭弹出框按钮
    $(function () {
        $('#addDialog').dialog('close');
        $('#editDialog').dialog('close');
        $('#roleResourDialog').dialog('close');
        $('#dg2').datagrid({loadFilter: pagerFilter1, fit: true});//.datagrid('loadData', getData());  为数据网格数据分页
        $('#sysMenu').datagrid({loadFilter: pagerFilter});//.datagrid('loadData', getData());
        $('#reportInfo').datagrid({loadFilter: pagerFilter, fitColumns: true});
        //$('#institutionalrolepermission').datagrid({loadFilter:pagerFilter});
        $('#reportOperate').datagrid({loadFilter: pagerFilter});

        $("#dg1").datagrid({
            loadMsg: '数据加载中,请稍后...',
            fitColumns: true,
            singleSelect: true,
            autoRowHeight: false,
            url: 'getAllSys_Auth_Role', //用户请求数据的URL
            columns: [[
                {field: 'id', title: '系统编号', width: 60, align: 'center'},
                {field: 'subjectName', title: '系统名称', width: 80, align: 'center'}
            ]]
        });


        $("#dg2").datagrid({
            loadMsg: '数据加载中,请稍后...',
            url: 'datagridRoleBySubId?subjectId=2&randSession=${authId}',
            fitColumns: true,
            singleSelect: true,
            rownumbers: true,
            toolbar: '#tb',
            autoRowHeight: false,
            pagination: true,
            pageSize: 25,
            pageList: [15, 25, 35],
            columns: [[
                {field: 'id', title: 'ID', width: 80, align: 'center', hidden: true},
                {field: 'subjectId', title: '系统编号', width: 80, align: 'center', hidden: true},
                {field: 'roleName', title: '角色名称', width: 80, align: 'center'},
                {field: 'description', title: '角色描述', width: 80, align: 'center'},
                {
                    field: 'isDelete',
                    title: '是否停用',
                    width: 80,
                    align: 'center',
                    formatter: function (value, row, index) {
                        if (value == 'N') {
                            return '否';
                        } else {
                            return '是';
                        }
                    }
                }
            ]]
        });

        $('#dg2').datagrid('getPager').pagination({ //设置分页功能栏
            //分页功能可以通过Pagination的事件调用后台分页功能来实现
            onRefresh: function () {
                selectRecordByName();
            }
        });

        //系统列表中的单击事件
        $("#dg1").datagrid({
            onClickRow: function (index, row) {
                subjectId = row.id;
                $.ajax({
                    url: 'findRoleBySubjectId',
                    type: 'POST', //GET
                    async: true, //或false,是否异步
                    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                    data: {"subjectId": row.id, "randSession": "${authId}"},
                    dataType: 'json', //返回的数据格式：json/xml/html/script/jsonp/text
                    success: function (data) {

                        var roleList = data.roleList;
                        var roleArray = [];
                        for (var i = 0; i < roleList.length; i++) {
                            var isdelete;
                            if (roleList[i].isDelete == 'Y') {
                                isdelete = '<span style="color: red">已停用</span>';
                            } else if (roleList[i].isDelete == 'N') {
                                isdelete = '未停用';
                            } else {

                            }
                            roleArray.push({
                                'id': roleList[i].id,
                                'subjectId': roleList[i].subjectId,
                                'roleName': roleList[i].roleName,
                                'description': roleList[i].description,
                                'isDelete': isdelete
                            });
                        }
                        $("#dg2").datagrid('loadData', roleArray);
                    }
                })
            }
        });
    });


    /*	function ajaxFindBySubjectId(){
            $.ajax({
                url : 'findRoleBySubjectId',
                type : 'POST', //GET
                async : true, //或false,是否异步
                contentType:'application/x-www-form-urlencoded; charset=UTF-8',
                data:{"subjectId":subjectId,"randSession":"${authId}"},
			dataType : 'json', //返回的数据格式：json/xml/html/script/jsonp/text
			success : function(data){
				var roleList = data.roleList;
				var roleArray = [];
				for(var i = 0;i<roleList.length;i++){
					var isdelete;
					if(roleList[i].isDelete == 'Y'){
						isdelete = '<span style="color: red">已停用</span>';
					}else if(roleList[i].isDelete == 'N'){
						isdelete = '未停用';
					}else{

					}
					roleArray.push({
						'id':roleList[i].id,
						'subjectId':roleList[i].subjectId,
						'roleName':roleList[i].roleName,
						'description':roleList[i].description,
						'isDelete':isdelete
					});
				}
				$("#dg2").datagrid('loadData',roleArray);
			}
		})
	}*/



    //点击取消按钮
    function cancel() {
        $('#roleResourDialog').dialog('close');
    }

    //点击新增上的重置按钮
    function resetforAdd() {
        $("#roleNameadd").val('');
        $("#roleDescadd").val('');
    }

    //点击修改上的重置按钮
    function resetforEdit() {
        $("#roleNameEdit").val('');
        $("#roleDescEdit").val('');
    }

    //点击查询按钮
    function selectRecordByName() {
        var randSession = "${authId}"
        if (subjectId == undefined) {
            $.messager.alert('操作提示', '请先选择系统!', 'warning');
        } else {
            var roleName = $("#roleName").val();
            $.ajax({
                url: 'getSys_Auth_RoleByLikeRoleName',
                type: 'POST', //GET
                async: true, //或false,是否异步
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                data: {"subjectId": 2, "roleName": roleName, "randSession": randSession},
                dataType: 'json', //返回的数据格式：json/xml/html/script/jsonp/text
                success: function (data) {
                    var roleList = data.roleList;
                    var roleArray = [];
                    for (var i = 0; i < roleList.length; i++) {
                        var isdelete;
                        if (roleList[i].isDelete == 'Y') {
                            isdelete = '<span style="color: red">已停用</span>';
                        } else if (roleList[i].isDelete == 'N') {
                            isdelete = '未停用';
                        } else {

                        }
                        roleArray.push({
                            'id': roleList[i].id,
                            'subjectId': roleList[i].subjectId,
                            'roleName': roleList[i].roleName,
                            'description': roleList[i].description,
                            'isDelete': isdelete
                        });
                    }
                    $("#dg2").datagrid('loadData', roleArray);
                }
            })
        }
    }


    //点击新增用户按钮
    function addRole() {
        if (subjectId == undefined) {
            $.messager.alert('操作提示', '请先选择系统!', 'warning');
        } else {
            $('#subjectIdAdd').val(subjectId);
            $('#addDialog').dialog('open');
            $('#addDialog').dialog({modal: true});
        }
    }


    //点击新增dialog上的保存按钮
    function saveForAddDialog() {
        var roleNameadd = $("#roleNameadd").val()
        var roleDescadd = $("#roleDescadd").val();
        if (roleNameadd.length == 0 || roleDescadd.length == 0) {
            $.messager.alert('操作提示', '请输入正确的角色名称和角色描述！', 'info');
            return;
        }
        if (roleNameadd.length > 255 && roleDescadd.length > 255) {
            $.messager.alert('操作提示', '角色名称和角色描述长度不得超过255', 'error');
            return;
        } else if (roleNameadd.length > 255) {
            $.messager.alert('操作提示', '角色名称不得超过255', 'error');
            return;
        } else if (roleDescadd.length > 255) {
            $.messager.alert('操作提示', '角色描述不得超过255', 'error');
            return;
        }
        $("#saveButtonId").linkbutton({disabled: true});
        $("#formForAddRole").form('submit', {
            url: 'addSys_Auth_Role',
            onSubmit: function () {
                if ($("#formForAddRole").form('validate')) {
                    $.messager.progress({
                        title: '请稍等',
                        msg: '正在保存角色...'
                    });
                    return true;
                } else {
                    $("#saveButtonId").linkbutton({disabled: false});
                    return false;
                }
            },
            success: function (res) {
                $.messager.progress('close');
                if (res == '1') {
                    $.messager.alert('', '新增成功！', 'info', function (r) {
                        $('#addDialog').dialog('close');
                        /*ajaxFindBySubjectId();*/
                        $('#dg2').datagrid('reload');
                    });
                } else if (res == '0') {
                    $.messager.alert('操作提示', '角色失败了', 'error');
                } else {
                    $.messager.alert('操作提示', '角色名称已存在', 'error');
                }
                $("#saveButtonId").linkbutton({disabled: false});
            }
        });
    }


    //点击修改角色按钮
    function editRole() {
        if (subjectId == undefined) {
            $.messager.alert('操作提示', '请先选择系统!', 'warning');
            return;
        }
        $('#subjectIdUpdate').val(subjectId);
        var row = $("#dg2").datagrid('getSelected'); //获取选中行对象
        if (row != null) { //如果选中
            //为修改dialog框中的文本框赋值
            document.getElementById("editId").value = row.id;
            isEdit_RoleName = row.roleName;

            roleName = row.roleName;
            roleDesc = row.description;
            $("#roleNameEdit").val(row.roleName);
            $("#roleDescEdit").val(row.description);

            $('#editDialog').dialog('open');
            $('#editDialog').dialog({
                modal: true
            });
        } else {
            $.messager.alert('操作提示', '请选择一条数据修改', 'info');
        }

    }


    //点击修改dialog上的保存按钮
    function saveForEditDialog() {
        if (isEdit_RoleName != $("#roleNameEdit").val()) { //如果修改前的用户中文名和修改后的用户中文名不一致，则表示用户修改了用户中文名
            $("#isEditRoleName").val("1");
        } else {
            $("#isEditRoleName").val("0");
        }
        var roleNameForm = $("#roleNameEdit").val();
        var roleDescForm = $("#roleDescEdit").val();
        if (roleNameForm == roleName && roleDescForm == roleDesc) {
            $.messager.alert('操作提示', '未做任何修改！', 'info');
            return;
        }

        var roleNameEdit = $("#roleNameEdit").val();
        var roleDescEdit = $("#roleDescEdit").val();
        if (roleNameEdit.length == 0 || roleDescEdit.length == 0) {
            $.messager.alert('操作提示', '请输入正确的角色名称和角色描述！', 'info');
            return;
        }
        if (roleNameEdit.length > 255 && roleDescEdit.length > 255) {
            $.messager.alert('操作提示', '角色名称和角色描述长度不得超过255', 'error');
            return;
        } else if (roleNameEdit.length > 255) {
            $.messager.alert('操作提示', '角色名称不得超过255', 'error');
            return;
        } else if (roleDescEdit.length > 255) {
            $.messager.alert('操作提示', '角色描述不得超过255', 'error');
            return;
        }
        $("#editButtonId").linkbutton({disabled: true});
        $("#formForEditRole").form('submit', {
            url: 'updateRoleNameAndRoleDesc',
            onSubmit: function () {
                if ($("#formForEditRole").form('validate')) {
                    $.messager.progress({
                        title: '请稍等',
                        msg: '正在保存角色...'
                    });
                    return true;
                } else {
                    $("#editButtonId").linkbutton({disabled: false});
                    return false;
                }
            },
            success: function (res) {
                $.messager.progress('close');
                if (res == '1') {
                    $.messager.alert('', '修改成功！', 'info', function (r) {
                        $('#editDialog').dialog('close');
                        /*ajaxFindBySubjectId();*/
                        $('#dg2').datagrid('reload');
                    });
                } else if (res == '0') {
                    $.messager.alert('操作提示', '修改用户失败了', 'error');
                } else {
                    $.messager.alert('操作提示', '角色名称已存在', 'error');
                }
                $("#editButtonId").linkbutton({disabled: false});
            }
        });
    }


    /*删除角色
    function remove() {
        var row = $("#dg1").datagrid('getSelected'); //获取选中行对象
        if (row != null) { //如果选中
            $.messager.alert('操作提示','是否要将此角色删除,如果删除，此角色将不能再使用','warning',
                function(r) {
                    $.ajax({
                        url : 'deleteSys_Auth_Role',
                        type : 'POST', //GET
                        async : true, //或false,是否异步
                        data : {"id" : row.id},
                        dataType : 'json', //返回的数据格式：json/xml/html/script/jsonp/text
                        success : function(data) {
                            if (data.result == '1'){ //如果返回1，删除成功
                                    $.messager.alert('','删除角色成功','info',function(r) {
                                            window.location.href = "getAllSys_Auth_Role";
                                    });
                            }else{ //否则删除失败
                                    $.messager.alert('操作提示','角色删除删除失败','error');
                            }
                        }
                    });
            });
        }else{
            $.messager.alert('操作提示', '请选择一条数据删除', 'info');
        }
    } */


    /*停用角色*/
    function stopRole() {
        var row = $("#dg2").datagrid('getSelected'); //获取选中行对象
        var randSession = "${authId}"
        if (row != null) { //如果选中
            if (row.isDelete.indexOf('已停用') >= 0) {
                $.messager.alert('操作提示', '该角色已被停用,请选择其他数据操作', 'info');
            } else {
                $.messager.alert('操作提示', '是否要停用此角色,如果停用，此角色将不能再使用', 'warning',
                    function (r) {
                        $.ajax({
                            url: 'stopSys_Auth_Role',
                            type: 'POST', //GET
                            async: true, //或false,是否异步
                            data: {"id": row.id, "randSession": randSession},
                            dataType: 'json', //返回的数据格式：json/xml/html/script/jsonp/text
                            success: function (data) {
                                if (data.result == '1') {
                                    $.messager.alert('', '停用角色成功', 'info', function (r) {
                                        /*ajaxFindBySubjectId();*/
                                        $('#dg2').datagrid('reload');
                                    });
                                } else {
                                    $.messager.alert('操作提示', '停用角色失败,有登录账户为 ' + data.result + ' 的用户正在使用该角色！请先锁定用户或修改用户的角色!', 'error');
                                }
                            }
                        });
                    });
            }
        } else {
            $.messager.alert('操作提示', '请选择一条数据删除', 'info');
        }
    }


    var roleResourceList;

    //点击角色资源管理按钮
    function roleResource() {
        var row = $("#dg2").datagrid('getSelected'); //获取选中行对象
        if (row != null) { //如果选中
            roleId = row.id;
            subjectId = row.subjectId;
            $.ajax({
                url: 'getSys_Menu',
                type: 'POST', //GET
                async: true, //或false,是否异步
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                data: {"subjectId": subjectId, "roleId": roleId, "randSession": "${authId}"},
                dataType: 'json', //返回的数据格式：json/xml/html/script/jsonp/text
                success: function (data) {
                    //显示菜单权限的数据
                    var menu = [];
                    for (var i = 0; i < data.menulist.length; i++) {
                        menu.push({
                            'id': data.menulist[i].id,
                            'subjectId': data.menulist[i].subjectId,
                            'name': data.menulist[i].name,
                            'url': data.menulist[i].url
                        });
                    }


                    //显示报表权限的数据
                    var report = []
                    var east2Huachen = '${east2Huachen}';
                    if (east2Huachen == 'on') {
                        for (var i = 0; i < data.reportlist.length; i++) {
                            report.push({
                                'id': data.reportlist[i].id,
                                'subjectId': data.reportlist[i].subjectId,
                                'code': data.reportlist[i].code,
                                'name': data.reportlist[i].name,
                                'batch': data.reportlist[i].batch,
                                'instruction': data.reportlist[i].instruction
                            });
                        }
                    } else {
                        for (var i = 0; i < data.reportlist.length; i++) {
                            report.push({
                                'id': data.reportlist[i].id,
                                'subjectId': data.reportlist[i].subjectId,
                                'code': data.reportlist[i].code,
                                'name': data.reportlist[i].name,
                                'batch': data.reportlist[i].batch,
                                'instruction': data.reportlist[i].instruction
                            });
                        }
                    }


                    //显示机构角色权限数据
                    /* var org = [];
                    for(var i =0;i<data.orglist.length;i++){
                        org.push({
                            'id' : data.orglist[i].id,
                            'orgId' : data.orglist[i].orgId,
                            'orgName' : data.orglist[i].orgName
                        });
                    }
                    $('#institutionalrolepermission').datagrid('loadData',org);  */


                    //显示报表操作权限数据
                    var reportOperate = [];
                    for (var i = 0; i < data.operatelist.length; i++) {
                        reportOperate.push({
                            'id': data.operatelist[i].id,
                            'subjectId': data.operatelist[i].subjectId,
                            'reportOperateCode': data.operatelist[i].reportOperateCode,
                            'reportOperateName': data.operatelist[i].reportOperateName
                        });
                    }

                    //回显已经为角色分配好的权限
                    roleResourceList = data.list;
                    $('#sysMenu').datagrid('loadData', menu);
                    $('#reportInfo').datagrid('loadData', report);
                    $('#reportOperate').datagrid('loadData', reportOperate);

                    //获取四个权限分配数据网格中的所有数据
                    var menuArray = $('#sysMenu').datagrid('getRows');
                    var reportArray = $('#reportInfo').datagrid('getRows');
                    //var orgArray = $('#institutionalrolepermission').datagrid('getRows');
                    var reportOperateArray = $('#reportOperate').datagrid('getRows');

                    //为四个权限tabs回显
                    $('#sysMenu').datagrid('unselectAll');
                    $('#reportInfo').datagrid('unselectAll');
                    //$('#institutionalrolepermission').datagrid('unselectAll');
                    $('#reportOperate').datagrid('unselectAll');

                    for (var i = 0; i < roleResourceList.length; i++) {

                        if (roleResourceList[i].resType == 'Menu') {
                            for (var j = 0; j < menuArray.length; j++) {
                                if (roleResourceList[i].resId == menuArray[j].id) {
                                    $('#sysMenu').datagrid('selectRow', j);
                                }
                            }
                        }

                        if (roleResourceList[i].resType == 'Report') {
                            for (var j = 0; j < reportArray.length; j++) {
                                if (roleResourceList[i].resId == reportArray[j].id) {
                                    $('#reportInfo').datagrid('selectRow', j);
                                }
                            }
                        }

                        /*  if(roleResourceList[i].resType == 'Org'){
                             for(var j = 0;j<orgArray.length;j++){
                                 if(roleResourceList[i].resId == orgArray[j].id){
                                     $('#institutionalrolepermission').datagrid('selectRow',j);
                                 }
                             }
                         } */

                        if (roleResourceList[i].resType == 'OperateReport') {
                            for (var j = 0; j < reportOperateArray.length; j++) {
                                if (roleResourceList[i].resId == reportOperateArray[j].id) {
                                    $('#reportOperate').datagrid('selectRow', j);
                                }
                            }
                        }

                    }

                }
            });

            $('#roleResourDialog').dialog('open');
            $('#roleResourDialog').dialog({modal: true});
        } else {
            $.messager.alert('操作提示', '请选择一条数据分配角色权限', 'info');
        }
    }


    function pagerFilter1(data) {
        if (typeof data.length == 'number' && typeof data.splice == 'function') {
            data = {
                total: data.length,
                rows: data
            }
        }
        var dg = $(this);
        var opts = dg.datagrid('options');
        var pager = dg.datagrid('getPager');
        pager.pagination({
            onSelectPage: function (pageNum, pageSize) {
                opts.pageNumber = pageNum;
                opts.pageSize = pageSize;
                pager.pagination('refresh', {
                    pageNumber: pageNum,
                    pageSize: pageSize
                });
                dg.datagrid('loadData', data);
            }
        });
        if (!data.originalRows) {
            data.originalRows = (data.rows);
        }
        var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
        var end = start + parseInt(opts.pageSize);
        data.rows = (data.originalRows.slice(start, end));
        return data;
    }


    //分页
    function pagerFilter(data) {
        if (typeof data.length == 'number' && typeof data.splice == 'function') { // is array
            data = {
                total: data.length,
                rows: data
            }
        }
        var dg = $(this);
        console.log(dg.attr("id"))
        var opts = dg.datagrid('options');
        var pager = dg.datagrid('getPager');
        pager.pagination({
            onSelectPage: function (pageNum, pageSize) {
                opts.pageNumber = pageNum;
                opts.pageSize = pageSize;
                pager.pagination('refresh', {
                    pageNumber: pageNum,
                    pageSize: pageSize
                });
                dg.datagrid('loadData', data);
            }
        });
        if (!data.originalRows) {
            data.originalRows = (data.rows);
        }
        var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
        var end = start + parseInt(opts.pageSize);
        data.rows = (data.originalRows.slice(start, end));
        //翻页后回显
        for (var i = 0; i < roleResourceList.length; i++) {

            if (roleResourceList[i].resType == 'Menu' && dg.attr("id") == "sysMenu") {
                for (var j = 0; j < data.rows.length; j++) {
                    if (roleResourceList[i].resId == data.rows[j].id) {
                        console.log(data.rows[j].id)
                        $('#sysMenu').datagrid('selectRecord', data.rows[j].id);
                    }
                }
            }

            if (roleResourceList[i].resType == 'Report' && dg.attr("id") == "reportInfo") {
                for (var j = 0; j < data.rows.length; j++) {
                    if (roleResourceList[i].resId == data.rows[j].id) {
                        $('#reportInfo').datagrid('selectRecord', data.rows[j].id);
                    }
                }
            }


            if (roleResourceList[i].resType == 'OperateReport' && dg.attr("id") == "reportOperate") {
                for (var j = 0; j < data.rows.length; j++) {
                    if (roleResourceList[i].resId == data.rows[j].id) {
                        $('#reportOperate').datagrid('selectRecord', data.rows[j].id);
                    }
                }
            }

        }

        return data;
    }

    //点击角色资源分配中的保存按钮
    function saveForRoleResourceDialog() {
        var randSession = "${authId}"
        var menuforsave = $('#sysMenu').datagrid('getSelections');
        var reportforsave = $('#reportInfo').datagrid('getSelections');
        //institutionalrolepermission,首字母缩写,机构角色权限
        //var Irpforsave = $('#institutionalrolepermission').datagrid('getSelections');
        var reportOperateforsave = $('#reportOperate').datagrid('getSelections');
        //因为有四个对象，所以js中用数组接收object中的值，这里比较复杂，多写注释。
        //标识
        var biaoshi = '';
        var jsonStr = '[';

        //菜单权限中要插入到角色资源对照表中的字段和数据
        for (var i = 0; i < menuforsave.length; i++) {
            var menuId = menuforsave[i].id;
            var menuUrl = menuforsave[i].url;
            var menuName = menuforsave[i].name;
            var menuSubjectId = menuforsave[i].subjectId;
            if (menuSubjectId != subjectId) {
                continue;
            }

            //标识为0时表示不为空
            biaoshi = '0';
            jsonStr = jsonStr + '{"subjectId":"' + subjectId + '","roleId":"' + roleId + '","resId":"' + menuId + '","resValue":"' + menuUrl + '","resValueName":"' + menuName + '","type":"Menu","biaoshi":"' + biaoshi + '"}'
        }

        //报表权限中要插入到角色资源对照表中的字段和数据 == 显示的是reportInfo表中的数据
        for (var i = 0; i < reportforsave.length; i++) {
            var codeforResId = reportforsave[i].id;
            var codeforResValue = reportforsave[i].code;
            var reportName = reportforsave[i].name;
            var reportSubjectId = reportforsave[i].subjectId;
            if (reportSubjectId != subjectId) {
                continue;
            }
            biaoshi = '0';
            jsonStr = jsonStr + '{"subjectId":"' + subjectId + '","roleId":"' + roleId + '","resId":"' + codeforResId + '","resValue":"' + codeforResValue + '","resValueName":"' + reportName + '","type":"Report","biaoshi":"' + biaoshi + '"}'
        }

        /* //机构角色权限中要插入到角色资源对照表中的字段和数据==显示的是sys_org表中的数据
        for (var i = 0; i < Irpforsave.length; i++) {
            var OrgforResId = Irpforsave[i].id;
            var OrgforResValue = Irpforsave[i].orgId;
            var OrgName = Irpforsave[i].orgName;
            biaoshi = '0';
            jsonStr = jsonStr + '{"roleId":"'+roleId+'","resId":"'+OrgforResId+'","resValue":"'+OrgforResValue+'","resValueName":"'+OrgName+'","type":"Org","biaoshi":"'+biaoshi+'"}'
        } */

        //报表操作权限中要插入到角色资源对照表中的字段和数据==显示的是SYS_REPORT_OPERATE表中的数据
        for (var i = 0; i < reportOperateforsave.length; i++) {
            var operatecodeforResId = reportOperateforsave[i].id;
            var operatecodeforResValue = reportOperateforsave[i].reportOperateCode;
            var operateName = reportOperateforsave[i].reportOperateName;
            var reportOperateSubjectId = reportOperateforsave[i].subjectId;
            if (reportOperateSubjectId != subjectId) {
                continue;
            }
            biaoshi = '0';
            jsonStr = jsonStr + '{"subjectId":"' + subjectId + '","roleId":"' + roleId + '","resId":"' + operatecodeforResId + '","resValue":"' + operatecodeforResValue + '","resValueName":"' + operateName + '","type":"OperateReport","biaoshi":"' + biaoshi + '"}'
        }
        if (menuforsave.length == 0 && reportforsave == 0 && reportOperateforsave == 0) {
            var biaoshiResId;
            var biaoshiResValue;
            var biaoshiResvalueName;
            biaoshi = '1';
            jsonStr = jsonStr + '{"subjectId":"' + subjectId + '","roleId":"' + roleId + '","resId":"' + biaoshiResId + '","resValue":"' + biaoshiResValue + '","resValueName":"' + biaoshiResvalueName + '","type":"biaoshitype","biaoshi":"' + biaoshi + '"}';
        }

        jsonStr = jsonStr.replace(/{/g, ',{').replace(',', '');
        jsonStr = jsonStr + ']';
        $.ajax({
            url: 'saveSysAuthRoleResourceButton',
            type: 'POST', //GET
            async: true, //或false,是否异步
            data: {"mydata": jsonStr, "randSession": randSession},
            dataType: 'json', //返回的数据格式：json/xml/html/script/jsonp/text

            success: function (data) {
                if (data == '1') {
                    $.messager.alert('', '分配成功', 'info',
                        function (r) {
                            $('#roleResourDialog').dialog('close');
                            //ajaxFindBySubjectId();
                            $('#dg2').datagrid('reload');
                        });
                } else {
                    $.messager.alert('操作提示', '分配失败', 'error');
                }
            }
        })
    }

</script>
</body>
</html>